<template>
  <el-card style="width: 100%; height: 70px">
    <div>
      <el-form :data="checkForm" :inline="true">
        <el-form-item style="font-weight: bold">
          <el-input v-model="checkForm.name" style="height: 35px" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <button type="button" class="btn btn-outline-primary" style="
              width: 80px;
              height: 35px;
              margin-top: -18px;
              margin-left: -20px;
            " @click="checkGoods">
          查询
        </button>
        <button type="button" class="btn btn-outline-warning" style="
              width: 80px;
              height: 35px;
              margin-top: -18px;
              margin-left: 20px;
            " @click="reset">
          重置
        </button>
      </el-form>
    </div>
  </el-card>
  <el-card style="margin-top: 2px">
    <button style="width: 100px" @click="deleteAllGoods" class="btn btn-outline-danger">
      批量删除
    </button>
    <button style="margin-left: 10px; width: 80px" @click="addDialogVisibleMethod" class="btn btn-outline-info">
      添加
    </button>
  </el-card>
  <el-card style="margin-top: 2px">
    <div>
      <el-table :data="tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
        " border style="width: 100%" header-row-class-name="table_header_class"
        @selection-change="handelSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" width="60px" align="center">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="img" label="商品图片" align="center">
          <template #default="scope">
            <img style="width:48px;height:48px" :src="scope.row.img" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" :show-overflow-tooltip="true" align="center" />
        <el-table-column prop="description" label="商品描述" align="center">
          <template #default="scope">
            <a @click="viewData(scope.row.description)" href="javascript:void(0);" style="text-decoration:none">详细信息</a>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="商品价格" align="center" :formatter="rounding">
          <template #default="scope">
            <span>{{ rounding(scope.row.price) }}&nbsp;元</span>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="计件单位" align="center" />
        <el-table-column prop="typeName" label="商品分类" align="center" />
        <el-table-column prop="sellerName" label="所属商家" align="center" />
        <el-table-column prop="count" label="销售数量" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-popconfirm title="您确认要删除嘛?" @confirm="deleteGoods(scope.row.id)" confirm-button-text="确认"
              cancel-button-text="取消" icon-color="red" style="height: 400px">
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
            <el-button @click="openUpdate(scope.row.id)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-card>
  <!--添加-->
  <el-dialog @close="cancelAdd" v-model="addDialogVisible" title="添加" style="font-weight: bold" width="40%">
    <el-form :model="addForm" label-width="120px">
      <el-form-item v-if="addRuleFlag" style="width: 400px; height: 30px">
        <div style="
              margin-left: 50px;
              color: rgb(220, 53, 69);
              width: 288px;
              height: 33px;
              border: 1px solid rgb(220, 53, 69);
              background-color: rgb(254, 242, 242);
            ">
          <div style="float: left">
            <el-icon style="margin: 6px" :size="20">
              <WarningFilled />
            </el-icon>
          </div>
          <div style="float: left; font-size: 14px; color: grey">
            <p>{{ addRuleMsg }}</p>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="商品名称" style="font-weight: bold">
        <el-input v-model="addForm.name" />
      </el-form-item>
      <el-form-item label="商品价格" style="font-weight: bold">
        <el-input v-model="addForm.price" />
      </el-form-item>
      <el-form-item label="计件单位" style="font-weight: bold">
        <el-input v-model="addForm.unit" />
      </el-form-item>
      <el-form-item label="商品分类" style="font-weight: bold">
        <el-select v-model="addForm.typeId" placeholder="">
          <el-option v-for="item in typeData" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属商家" style="font-weight: bold">
        <el-select  disabled v-model="addForm.sellerId" placeholder="">
          <el-option :label="user.name" :value="user.id" :key="user.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="销售数量" style="font-weight: bold">
        <el-input v-model="addForm.count" />
      </el-form-item>
      <el-form-item label="图片">
        <div style="width: 200px; height: 200px">
          <el-upload class="avatar-uploader" action="http://localhost:8080/file/upload" :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="addForm.img" :src="addForm.img" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="商品描述">
        <div id="editor" style="width:100%"></div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addGoods"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>

  <!--修改-->
  <el-dialog @close="cancelUpdate" v-model="updateDialogVisible" title="修改" style="font-weight: bold" width="40%">
    <el-form :model="updateForm" label-width="120px">
      <el-form-item v-if="updateRuleFlag" style="width: 400px; height: 30px">
        <div style="
              margin-left: 50px;
              color: rgb(220, 53, 69);
              width: 288px;
              height: 33px;
              border: 1px solid rgb(220, 53, 69);
              background-color: rgb(254, 242, 242);
            ">
          <div style="float: left">
            <el-icon style="margin: 6px" :size="20">
              <WarningFilled />
            </el-icon>
          </div>
          <div style="float: left; font-size: 14px; color: grey">
            <p>{{ updateRuleMsg }}</p>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="商品名称" style="font-weight: bold" prop="name">
        <el-input v-model="updateForm.name" />
      </el-form-item>
      <el-form-item label="商品价格" style="font-weight: bold">
        <el-input v-model="updateForm.price" />
      </el-form-item>
      <el-form-item label="计件单位" style="font-weight: bold">
        <el-input v-model="updateForm.unit" />
      </el-form-item>
      <el-form-item label="商品分类" style="font-weight: bold">
        <el-select v-model="updateForm.typeId" placeholder="">
          <el-option v-for="item in typeData" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属商家" style="font-weight: bold">
        <el-select disabled v-model="updateForm.sellerId" placeholder="">
          <el-option v-for="item in sellerData" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品销量" style="font-weight: bold">
        <el-input v-model="updateForm.count" />
      </el-form-item>
      <el-form-item label="商品图片">
        <div style="width: 200px; height: 200px">
          <el-upload class="avatar-uploader" action="http://localhost:8080/file/upload" :show-file-list="false"
            :on-success="handleUpdateSuccess">
            <img v-if="updateForm.img" :src="updateForm.img" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="商品描述">
        <div id="editor" style="width:100%"></div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateGoods"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>

  <!--商品介绍-->
  <el-dialog title="商品介绍" v-model="editorVisble" @close="cancel" width="47%">
    <div v-html="dataView" class="w-e-text"></div>
  </el-dialog>

  <!--分页-->
  <div>
    <el-pagination style="margin-left: 730px" small background @current-change="currentChange"
      :current-page="currentPage" :page-size="pageSize" layout="prev, pager, next" :total="tableData.length"
      class="mt-4" />
  </div>
</template>

<script>
import {
  getAll,
  selectGoods,
  addOne,
  deleteOne,
  deleteAll,
  selectOne,
  updateOne,
  conditionQuery,
} from "../../api/index";

import E from "wangeditor"

let editor
function initWangEditor(content) {
  setTimeout(() => {
    if (!editor) {
      editor = new E("#editor")
      editor.config.placeholder = "请输入内容"
      editor.config.uploadFileName = "file"
      editor.config.uploadImgServer = "http://localhost:8080/file/wang/upload"
      editor.create()
    }
    editor.txt.html(content)
  }, 0)

}

export default {
  data() {
    return {
      typeData: [],
      sellerData:[],
      user: {},
      checkForm: {
        name: "",
      },
      tableData: [],
      currentPage: 1,
      pageSize: 8,
      addDialogVisible: false,
      updateDialogVisible: false,
      addForm: {
        username: "",
        name: "",
        phone: "",
        email: "",
        avatar: "",
      },
      updateForm: {},
      addRuleFlag: false,
      addRuleMsg: "",
      updateRuleFlag: false,
      updateRuleMsg: "",
      ids: [],
      flag: true,
      editorVisble: false,
      dataView: []
    };
  },
  created() {
    this.user = JSON.parse(localStorage.getItem("user"))
    this.loadData();
    this.loadSellerData();
    this.loadTypeData()
    console.log(this.user);
  },
  methods: {
    async loadTypeData() {
      await getAll("type").then(res => {
        if (res.code === 200) {
          this.typeData = res.data
          console.log(this.typeData);
        } else {
          this.$message.error(res.message)
        }
      })
    },
    loadData() {
      selectGoods("goods", this.user.id).then(res => {
        if (res.code === 200) {
          this.tableData = res.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    currentChange(val) {
      this.currentPage = val;
    },
    handleAvatarSuccess(response) {
      console.log(response);
      this.addForm.img = response.data;
    },
    handleUpdateSuccess(response) {
      this.updateForm.img = response.data;
    },
    addDialogVisibleMethod() {
      (this.addForm.img = ""),
        (this.addForm.unit = ""),
        (this.addForm.name = ""),
        (this.addForm.price = ""),
        this.addForm.typeId = "",
        this.addForm.sellerId = this.user.id,
        (this.addForm.count = ""),
        (this.addRuleFlag = false),
        (this.addRuleMsg = ""),
        (this.addDialogVisible = true);
      initWangEditor("")
    },
    loadSellerData(){
        getAll("seller").then(res=>{
            if (res.code===200) {
                this.sellerData = res.data    
            }else{
                this.$message.error(res.message)
            }
        })
      },
    addGoods() {
      this.addForm.description = editor.txt.html()
      if (this.addForm.name === "") {
        this.addRuleFlag = true,
          this.addRuleMsg = "商品名称为空"
      } else if (this.addForm.price === "") {
        this.addRuleFlag = true,
          this.addRuleMsg = "商品价格为空"
      } else if (this.addForm.unit === "") {
        this.addRuleFlag = true
        this.addRuleMsg = "计件单位为空"
      } else if (this.addForm.typeId === "") {
        this.addRuleFlag = true,
          this.addRuleMsg = "请选择商品分类"
      } else if (this.addForm.sellerId === "") {
        this.addRuleFlag = true,
          this.addRuleMsg = "请选择所属商家"
      } else if (this.addForm.count === "") {
        this.addRuleFlag = true,
          this.addRuleMsg = "商品销量为空"
      } else if (this.addForm.img === "") {
        this.addRuleFlag = true,
          this.addRuleMsg = "请上传头像"
      } else {
        addOne("goods", this.addForm).then(res => {
          if (res.code === 200) {
            this.addDialogVisible = false,
              this.$message.success(res.message),
              this.loadData()
          } else {
            this.addDialogVisible = false
            this.$message.error(res.message)
          }
        })
      }
    },
    deleteGoods(id) {
      deleteOne("goods", id).then((res) => {
        if (res.code === 200) {
          this.loadData();
          this.$message.success(res.message);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    deleteAllGoods() {
      if (this.ids.length === 0) {
        this.$message.info("未选中");
      } else {
        this.$confirm("你确认要删除嘛？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "error",
        })
          .then(() => {
            deleteAll("goods", this.ids).then((res) => {
              if (res.code === 200) {
                this.loadData();
                this.$message.success(res.message);
              } else {
                this.$message.error(res.message);
              }
            });
          })
          .catch(() => {

            this.$message.info("取消删除");
          });
      }
    },
    handelSelectionChange(val) {
      this.ids = []
      for (let i = 0; i < val.length; i++) this.ids[i] = val[i].id;
    },
    openUpdate(id) {
      this.updateRuleFlag = false,
        this.updateRuleMsg = "",
        console.log(this.tableData);
      selectOne("goods", id).then((res) => {
        if (res.code === 200) {
          this.updateForm = res.data;
          initWangEditor(this.updateForm.description || "")
          this.updateDialogVisible = true;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    updateGoods() {
      this.updateForm.description = editor.txt.html()
      if (this.updateForm.name === "") {
        this.updateRuleFlag = true,
          this.updateRuleMsg = "商品名称为空"
      } else if (this.updateForm.price === "") {
        this.updateRuleFlag = true,
          this.updateRuleMsg = "商品价格为空"
      } else if (this.updateForm.unit === "") {
        this.updateRuleFlag = true,
          this.updateRuleMsg = "计件单位为空"
      } else if (this.updateForm.typeId === "") {
        this.updateRuleFlag = true,
          this.updateRuleMsg = "商品分类为空"
      } else if (this.updateForm.sellerId === "") {
        this.updateRuleFlag = true,
          this.updateRuleMsg = "所属商家为空"
      } else if (this.updateForm.count === "") {
        this.updateRuleFlag = true,
          this.updateRuleMsg = "商品销量为空"
      } else if (this.updateForm.img === "") {
        this.updateRuleFlag = true,
          this.updateRuleMsg = "请上传图片"
      } else {
        updateOne("goods", this.updateForm).then((res) => {
          if (res.code === 200) {
            this.$message.success(res.message);
            (this.updateDialogVisible = false), this.loadData();
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    reset() {
      this.checkForm.name = ""
    },
    checkGoods() {
      if (this.checkForm.name === "") {
        this.loadData();
      } else {
        conditionQuery("goods", this.checkForm).then((res) => {
          if (res.code === 200) {
            this.tableData = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    rounding(price) {
      return parseFloat(price).toFixed(2)
    },
    viewData(data) {
      this.dataView = data
      this.editorVisble = true
    },
    cancel() {
      this.editorVisble = false
      this.$router.go(0)
    },
    cancelAdd() {
      this.addDialogVisible = false
      this.$router.go(0)
    },
    cancelUpdate() {
      this.updateDialogVisible = false
      this.$router.go(0)
    }

  },
};
</script>

<style lang="less" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/deep/ .table_header_class th {
  background-color: #f0f2ff;
  color: #8c99ff;
  text-align: center;
  height: 50px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>